#!/bin/bash
#
# Init file for SSH Public Keys Download Client
#
# chkconfig: 345 98 02
# description: SSH Public Keys Download Client

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.


# Modify this line to specify the user (default is root)
user=root

mountdir=$(mktemp -d)

# If lable name is other than config, please change the below line as required
DefaultDisk=/dev/disk/by-label/config-2

SSHKey_File=$mountdir/cloudstack/metadata/public-keys.txt
keys_received=0

function prepare_mount
{
    if [ ! -e $mountdir ]; then
        mkdir $mountdir
        chmod 700 $mountdir
    fi

    if [ -e $DefaultDisk ]; then
        Disk=$DefaultDisk
    else
        BLOCK_DEVICE=$(blkid -t LABEL='config-2' /dev/hd? /dev/sd? /dev/xvd? /dev/vd? -o device)
        if [ -n $BLOCK_DEVICE ]; then
            Disk=$BLOCK_DEVICE
        else
            logger -t "cloud" "Unable to get SSH public key: Config drive not found"
            exit 1
        fi
    fi

    mount -r $Disk $mountdir
    if [ $? -ne 0 ]; then
        echo "Failed mounting $Disk to /mnt/configdrive"
        exit 1
    fi
}

function remove_mount
{
  umount $mountdir
}

prepare_mount


if [ -f $SSHKey_File ]
then
    publickey=$(cat $SSHKey_File)
    publickey=$(echo $publickey | tr -d '\r')
    remove_mount

    if [ -z "$publickey" ]; then
        logger -t "cloud" "Did not receive any keys"
        exit 1
    fi
else
    remove_mount
    logger -t "cloud" "Did not receive any keys"
    exit 1
fi

homedir=$(getent passwd $user|awk -F ":" '{print $6}')
sshdir=$homedir/.ssh
authorized=$sshdir/authorized_keys

if [ ! -e $sshdir ]; then
    mkdir $sshdir
    chmod 700 $sshdir
fi

if [ ! -e $authorized ]; then
    touch $authorized
    chmod 600 $authorized
fi


cat $authorized|grep -v "$publickey"|tee $authorized > /dev/null
echo "$publickey" >> $authorized

which restorecon && restorecon -R -v $sshdir

exit 0
